from PySide6.QtWidgets import QWidget, QPushButton, QLabel, QFileDialog
from PySide6.QtGui import QPixmap
from ...Input import Input
import time
import os.path as ospath
from config import config
from util.Mouse import MouseUtil
import shutil
from PIL import ImageGrab, ImageQt


class PicContain(QWidget):
    def __init__(self, parent: QWidget):
        super(PicContain, self).__init__(parent)

        lineHeight = int(parent.height() / 2)

        self.picPath = ospath.join(
            config.SCRIPT_PIC_RECOGNITION_PIC_PATH,
            str(int(round(time.time() * 1000))) + '.png'
        )

        # x
        self.inputX = Input(self, 'x', 6, 'number')
        self.inputX.text = 0
        self.inputX.setFixedHeight(lineHeight)
        self.inputX.setPos(0, 0)

        # y
        self.inputY = Input(self, 'y', 6, 'number')
        self.inputY.text = 0
        self.inputY.setFixedHeight(lineHeight)
        self.inputY.setPos(self.inputX.x() + self.inputX.width(), 0)

        # 宽
        self.inputWidth = Input(self, '宽', 6, 'number')
        self.inputWidth.text = 0
        self.inputWidth.setFixedHeight(lineHeight)
        self.inputWidth.setPos(self.inputY.x() + self.inputY.width(), 0)

        # 高
        self.inputHeight = Input(self, '高', 6, 'number')
        self.inputHeight.text = 0
        self.inputHeight.setFixedHeight(lineHeight)
        self.inputHeight.setPos(self.inputWidth.x() + self.inputWidth.width(), 0)

        # 图片
        self.labImg = QLabel(self)
        self.labImg.setFixedSize(lineHeight, lineHeight)
        self.labImg.setStyleSheet(
            "QLabel{background:white;}"
        )
        self.labImg.setGeometry(0, lineHeight, self.labImg.width(), self.labImg.height())

        self.btnChoosePic = QPushButton(self)
        self.btnChoosePic.setText('选择图片')
        self.btnChoosePic.clicked.connect(self.choosePic)
        self.btnChoosePic.setGeometry(
            self.labImg.geometry().right() + 10, lineHeight,
            70, lineHeight
        )

        self.btnGrab = QPushButton(self)
        self.btnGrab.setText('截取屏幕')
        self.btnGrab.clicked.connect(self.startGrab)
        self.btnGrab.setGeometry(
            self.btnChoosePic.geometry().right() + 10, lineHeight,
            70, lineHeight
        )

        self.btnTrack = QPushButton(self)
        self.btnTrack.setText('选择区域')
        self.btnTrack.clicked.connect(self.startClickListener)
        self.btnTrack.setGeometry(self.btnGrab.geometry().right() + 10, lineHeight, 70, lineHeight)

        self.setFixedSize(self.inputHeight.geometry().right(), parent.height())

    def onMouseClick(self, x, y, width, height, button):
        self.inputX.text = x
        self.inputY.text = y
        self.inputWidth.text = width
        self.inputHeight.text = height

    def startClickListener(self):
        MouseUtil.listenArea(self.onMouseClick)

    def choosePic(self):
        imgName, imgType = QFileDialog.getOpenFileName(
            self, "选择图片", "",
            "Image Files (*.png *.jpeg *.bmp);;All Files(*)")
        if imgName is None or imgName == '':
            return

        # 将需要识别的图片保存到应用内部存储地址
        shutil.copy(imgName, self.picPath)

        self.labImg.setPixmap(QPixmap(imgName).scaled(self.labImg.width(), self.labImg.height()))

    def grabScreen(self, x, y, button, pressed):
        if pressed:
            self.tempLeft = int(x)
            self.tempTop = int(y)
        else:
            left = self.tempLeft
            top = self.tempTop
            right = int(x)
            bottom = int(y)
            if x < left:
                right = left
                left = int(x)

            if y < top:
                bottom = top
                top = int(y)

            # 将需要识别的图片保存到应用内部存储地址
            recoImg = ImageGrab.grab(bbox=(left, top, right, bottom))
            recoImg.save(self.picPath)
            self.labImg.setPixmap(ImageQt.toqpixmap(recoImg))
            return False

    def startGrab(self):
        MouseUtil.listenArea(self.grabScreen)

    @property
    def data(self):
        return {
            "x": int(self.inputX.text),
            "y": int(self.inputY.text),
            "width": int(self.inputWidth.text),
            "height": int(self.inputHeight.text),
            "pic": self.picPath
        }

    @data.setter
    def data(self, data):
        self.setData(data)
        self.inputX.text = data['x']
        self.inputY.text = data['y']
        self.inputWidth.text = data['width']
        self.inputHeight.text = data['height']
        self.labImg.setPixmap(QPixmap(data['pic']))
        self.picPath = data['pic']
